<template>
  <div>
    <el-button @click="showDialog">新增</el-button>
    <el-table :data="modelValue" style="width: 100%">
      <el-table-column prop="index" label="序号" width="80" type="index" align="center" />
      <el-table-column prop="name" label="名称" width="150" align="center">
        <template #default="{row}">
          {{ row.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="area" label="面积(㎡)" width="120" align="center">
        <template #default="{row}">
          {{ row.area ? `${row.area} ㎡` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="location" label="点位" width="200" align="center" show-overflow-tooltip />
      <el-table-column prop="problems" label="问题" align="center">
        <template #default="{row}">
          <div v-if="row.problems && row.problems.length > 0">
            <el-tag
                v-for="problem in row.problems"
                :key="problem"
                style="margin-right: 5px; margin-bottom: 5px">
              {{ getProblemLabel(problem) }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="问题描述" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="180">
        <template #default="{row, $index}">
          <el-button size="small" @click="handleEdit($index)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑记录' : '新增记录'" width="50%">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="名称" required>
          <el-input v-model="formData.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="面积(㎡)" required>
          <el-input-number
              v-model="formData.area"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
              placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="点位" required>
          <el-input
              v-model="formData.location"
              placeholder="点击地图选择位置"
              @click="openMapPicker">
            <template #append>
              <el-button @click="openMapPicker">选择位置</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="问题">
          <el-checkbox-group v-model="formData.problems">
            <el-checkbox
                v-for="option in problemOptions"
                :key="option.value"
                :label="option.value">
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入详细问题描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, ref, watch } from "vue";
import { Form } from "ant-design-vue";
import { ElMessage } from 'element-plus';

const formItemContext = Form.useInjectFormItemContext();
const emits = defineEmits(["update:modelValue", "change", "blur"]);
const getProblemLabel = (value: string) => {
  const option = problemOptions.find(opt => opt.value === value);
  return option ? option.label : value;
};

const problemOptions = [
  {
    label: '儿童娱乐设施不足或破损（沙坑、滑梯）',
    value: 'children_entertainment'
  },
  {
    label: '体育健身设施不足或破损（既有小区场地配置健身器材、健身步道，新建小区场地配置5人制足球、篮球、排球、兵乓球、门球等球类场地，在紧急情况下可以转换为应急避难场所）',
    value: 'sports_facilities'
  },
  {
    label: '不符合无障碍设计要求（主要出入口应设置无障碍出入口和提示盲道，游步道应为无障碍通道，轮椅园路纵坡不应大于4%，轮椅专用道不应大于8%，休憩设施不宜设置高于450mm的台阶，必须设置时应同时设置轮椅坡道和提示盲道，休息座椅应留有轮椅停留空间，林下铺装活动场地林下净空不得低于2.2m，儿童活动场地周围不宜种植遮挡视线的树木）',
    value: 'accessibility'
  },
  {
    label: '场地存在私搭乱建问题',
    value: 'illegal_construction'
  },
  {
    label: '无问题',
    value: 'no_problem'
  }
];
const props = defineProps({
  componentSchema: {
    default: () => ({}),
    type: Object,
  },
  modelValue: {
    default: () => ([]),
    type: Array,
  },
});

const dialogVisible = ref(false);
const isEdit = ref(false);
const currentIndex = ref(-1);

const formData = ref({
  name: '',
  area: null,
  location: '',
  problems: [],
  description: ''
});

const showDialog = () => {
  isEdit.value = false;
  formData.value = {
    name: '',
    area: null,
    location: '',
    problems: [],
    description: ''
  };
  dialogVisible.value = true;
};

const handleEdit = (index) => {
  isEdit.value = true;
  currentIndex.value = index;
  formData.value = { ...props.modelValue[index] };
  dialogVisible.value = true;
};

const handleDelete = (index) => {
  const newData = [...props.modelValue];
  newData.splice(index, 1);
  emits("update:modelValue", newData);
  formItemContext.onFieldChange();
};

const handleConfirm = () => {
  if (!formData.value.name || formData.value.area === null || !formData.value.location) {
    ElMessage.error('请填写名称、面积和点位');
    return;
  }

  // 如果选择了"无问题"，则清空其他问题选项
  if (formData.value.problems.includes('无问题')) {
    formData.value.problems = ['无问题'];
  }

  const newData = [...props.modelValue];

  if (isEdit.value) {
    newData[currentIndex.value] = formData.value;
  } else {
    newData.push(formData.value);
  }

  emits("update:modelValue", newData);
  formItemContext.onFieldChange();
  dialogVisible.value = false;
};

const openMapPicker = () => {
  // 这里实现地图选点逻辑
  // 示例：模拟选择位置
  formData.value.location = "北京市朝阳区XXX街道";
  // 实际项目中应集成地图SDK，如高德、百度地图等
};

// 保留原有的 watch 逻辑
const value = ref("");
watch(value, (e) => {
  emits("update:modelValue", e);
  formItemContext.onFieldChange();
});

watch(
    () => props.modelValue,
    (e) => {
      if (e && e.length > 0) {
        value.value = e;
      }
    },
    { immediate: true }
);
</script>


<style scoped>
.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.el-checkbox {
  display: block;
  margin-bottom: 10px;
}
</style>


